import { createStore } from 'vuex'
import persist from 'vuex-persistedstate'
export default createStore({
  state: {
    goods: []
  },
  getters: {
    count(state) {
      let num = 0
      state.goods.forEach(item => {
        num += item.num
      })
      return num
    }
  },

  mutations: {
    addGood(state, good) {
      let flag = false
      if(state.goods.length === 0) {
        state.goods.push(good)
      } else {
        state.goods.forEach((item, i) => {
          if(good.id === item.id) {
            state.goods[i].num += good.num
            flag = true
          } 
        })

        if(!flag) {
          state.goods.push(good)
        }
      }
    },

    del(state, arr) {
      for(let i = 0; i<state.goods.length; i++) {
        arr.forEach(item => {
          if(state.goods[i].id == item.id) {
            state.goods.splice(i, 1)
          }
        })
      }
    },

    changeGoods(state, arr) {
      state.goods = arr
    }
  },
  actions: {
  },
  modules: {
  },

  plugins: [
    persist()
  ]
})
